package collections;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.google.common.collect.HashMultiset;
import com.google.common.collect.Lists;
import com.google.common.collect.Multiset;
import com.google.common.collect.Multiset.Entry;

public class MultiSetDemo {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		//一个颜色的列表，记录了颜色的出现次数，现在要根据颜色不同，计算每个颜色的出现次数
		ArrayList<String> colors = Lists.newArrayList("red","orange","yellow","green","blue",
				"purple","white","yellow","green","red","orange",
				"black","white","yellow","green","red","orange","black",
				"white","yellow","green","orange","yellow","green",
				"yellow","green","orange");
		
		System.out.println(oldMethod(colors));
		
		
		//使用新容器Multiset
		Multiset<String> colorSet = HashMultiset.create();
		colorSet.addAll(colors);
		System.out.println(colorSet);
		
		//可以检索一个颜色的出现次数
		System.out.println(colorSet.count("black"));
		//可以直接设置一个颜色的次数
		colorSet.add("lightGrey",10);
		//可以直接设置一个颜色的次数
		colorSet.setCount("darkGrey", 8);
		System.out.println(colorSet);
		
		//快速删除掉一个颜色的办法
		colorSet.setCount("black", 0);
		System.out.println(colorSet);
		//颜色出现的次数减1，可以自定义减几
		colorSet.remove("darkGrey", 1);
		
		//在Multiset中，迭代，或者size()方法，返回的都是包含了所有颜色重复出现的原始集合
		for (String color : colorSet) {
			System.out.print(color+"\t");
		}
		System.out.println();
		System.out.println(colorSet.size());
		
		//想要知道总共有几种颜色，使用
		System.out.println(colorSet.elementSet());
		System.out.println(colorSet.elementSet().size());
		
		
		for (Entry<String> entry : colorSet.entrySet()) {
			System.out.print(entry.getElement()+"\t");
			System.out.print(entry.getCount()+"\t");
			System.out.println();
		}
		System.out.println();
	}
	
	public static HashMap<String, Integer> oldMethod(List<String> seperateColor) {
		HashMap<String, Integer> colors=new HashMap<String, Integer>();
		for (String color : seperateColor) {
			Integer colorCount = colors.get(color);
			if (colorCount==null) {
				colors.put(color, 1);
			}else {
				colors.put(color, colorCount+1);
			}
		}
		return colors;
	}

}
